<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2019/9/6
 * Time: 16:21
 */
namespace app\admin\controller;
use think\Db;
use think\Loader;
use tixian\WX\Weixin;
use tixian\WX\Ali;
use think\Request;

class Withdraw extends Base {
    // 微信提现配置
    public $wx_config = [
        'key' => 'wVNAxT3I8dJl1nabp2t6KfNt0ufvurr4', // 商户平台设置的秘钥
        'mch_appid' => 'wx1ddf922fb0cd6ca7', // 商户号的appid
        'mchid' => '1557073621' // 商户号
    ];
    
    // 支付宝提现配置 rsaPrivateKey:私钥  alipayrsaPublicKey:支付宝生成的支付宝公钥
    public $ali_config = [
        'appId' => '2021001192604261',
        'rsaPrivateKey' => 'MIIEpAIBAAKCAQEAhNJ9Q2PcHxZaFrWF1H0zYUadTxzRmXMAt8VVOkEHShNJVUfKoJ9qPmpWjUxJPPODQoLy9OAYY+mgwY4tEuROeBwJ2Ak4/81pl8suP7DLXf1wKKESEVgYJ2q9BCGqv91ZPTgPhdidn/P5Oq3wf/rLfPvrrkvZ2Gknoq1XcRDZdXqYzd9gml/nXPP/p8QG4xazuA+fIY2mSe6OLFzAV1QeCCgtTx4MmLc27b9WdlF5Os+ubZmOemt6m8u/nnoR8CGucuoQIsQzjwXy256dl/mOrz0QTub5Cwa24ga/wReEut/UVaAWuelMBCyr9ebJhjohnURJ1R/x6uRkxUEH8HX8xQIDAQABAoIBAFZ8gRhKg+CyO0MiO9ybEcO7qV8EUu7qVYNUOSTPhyGS4WNodeaVJycxMt6a1+2aWtQKVI1jBj64t/aQz4THqNjI2RgVGUpnxOQUZy8Nvb6b8lZiW1Nz23Z/KEjyay63wQ393Q24eRrYUGcHL90Fv07I8zPxLA6gmjBxUsjKwe6eT11yv9dk2Z8tu7mDZmh4QXccYqR38rxI6y5FYzOKdDbWB9fvVoUGEydtzJBKa2ynOVexmtOX1/GJsPwPHOsQY3+9I0tz7ksCi3tNIsPyREEqDK9QDsuc6D9dymEeuuSrFFWKr2vUuPsGq/81rQEi7MxlT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qhe8udEQoYJ2oRwq4vtRITDc2KZxkysnFFiCBLTBms8FimzRmylt+tM+ibLG5pUuTY2Vik9k+h79ceSySzE0OFsyNnV1Wi7JxzQfySd9Jjg+VxcjOLQKhJ2LRLCd2QOmRgOFZGvodl/7N/BE03AEzgwieLCC0Owyv7L0W/D3iGmw1It9ZR3fI0FDkDxV/Dxhxy9NWvYlbrtL29PA0CNzQ5hM/ejgPB1QqVC3Cna9wIDAQAB'
    ];
    
    public function index(){
        if(request()->isAjax()){
            extract(input());
            $map =array();
            $page = input('page') ? input('page'):1;
            $limit = input("limit")?input("limit"):10;// 获取总条数;
            if(isset($keyword)&&$keyword!="")
            {
                $map['uuu.user_username|uuu.user_phone'] = ['like',"%" . $keyword . "%"];
            }
            if(isset($withdraw_status)&&$withdraw_status!="")
            {
                $map['withdraw_status'] = $withdraw_status;
            }
            if(isset($start)&&$start!=""&&isset($end)&&$end=="")
            {
                $map['a.withdraw_create_time'] = ['>= time',$start];
            }
            if(isset($end)&&$end!=""&&isset($start)&&$start=="")
            {
                $map['a.withdraw_create_time'] = ['<= time',$end];
            }
            if(isset($start)&&$start!=""&&isset($end)&&$end!="")
            {
                $map['a.withdraw_create_time'] = ['between time',[$start,$end]];
            }

            $count = Db::table('up_withdraw')->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.withdraw_user_id','left')
                ->where($map)
                ->count();
            $lists = Db::table('up_withdraw')->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.withdraw_user_id','left')
                ->where($map)
                ->field('uuu.user_username,uuu.user_phone,uuu.user_id,a.*')
                ->order('withdraw_create_time desc')
                ->page($page, $limit)
                ->select();//计算总页面
            $count2 = Db::table('up_withdraw')->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.withdraw_user_id','left')
                ->where($map)->column('withdraw_id');// 获取总条数
            $str = '';
            if($count2){
                $str = implode($count2,',');
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'count2' => $str, 'data' => $lists]);        }
        return $this->fetch();
    }
    
    /**
     * 通过
     * @return \think\response\Json
     */
    public function adopt(){
        $ids = input('id');
        $info = Db::table('up_withdraw')->where('withdraw_id', $ids)->find();
//        // 提现手续费
//        $dis = Db::table('up_about')->where('about_id', 14)->value('about_tixian_dis');
//        $ratio = 100 - $dis;
//        $price = $info['withdraw_money'] * $ratio * 0.01; // 实际到账金额
        $price = $info['withdraw_money']*0.006 ; // 实际到账金额

        // todo:1 调取微信/支付宝提现接口  2 提现成功修改提现申请状态  3 提现成功参入到order表  4 减用户余额
        if($info['withdraw_type'] == 1){
            Loader::import('tixian.Weixin',EXTEND_PATH,'.php');
            $wxtx = new Weixin($this->wx_config);
            $res = $wxtx->wxTiXian($info['withdraw_num'], $info['withdraw_openid'], $price);
            $return_code = (string)$res->return_code;
            $result_code = (string)$res->result_code;
            $return_code = trim(strtoupper($return_code));
            $result_code = trim(strtoupper($result_code));
            if($return_code == 'SUCCESS' && $result_code == 'SUCCESS'){
                $success = 1;
            }else{
               $success = 0;
               $msg = (string)$res->return_msg;
            }
        }else{ // 支付宝
            $data = [
                'out_biz_no' => $info['withdraw_num'], // 订单号
                'payee_account' => $info['withdraw_zh'], // 支付宝账号
                'amount' => $price, // 交易金额
//                'payee_real_name' => $info['withdraw_rel_name'] // 真实姓名
            ];
            Loader::import('tixian.Ali',EXTEND_PATH,'.php');
            $ali = new Ali($this->ali_config);
            $request = $ali->aliTiXian($data);
            if($request['code'] == 1){
                $success = 1;
            }else{
                $success = 0;
                // $result->$responseNode->sub_msg 这个参数 是返回的错误信息
                $msg = $request['msg'];
            }
        }
        
        if($success == 1){
                //插入钱包明细
                $result['user_id'] = $info['withdraw_user_id'];
                $result['balance_type'] = $info['withdraw_type'];
                $result['balance_time'] = date('Y-m-d H:i:s');
                if($info['withdraw_type']==1){
                    $result['balance_title'] ="微信提现";
                }elseif ($info['withdraw_type']==2){
                    $result['balance_title'] ="支付宝提现";
                }
                $result['balance_num'] = date('YmdHis') . str_pad(mt_rand(1, 99999999), 4, '0', STR_PAD_LEFT);
                $result['balance_price'] = $info['withdraw_money'];
                $result['balance_status'] = 2;
                $result['balance_jia_jian'] = 1;
                $result['balance_xs'] = 1;
                Db::table('up_user_balance')->insertGetId($result);
            Db::startTrans();
            try{
                // 修改提现订单状态和审核时间
                Db::table('up_withdraw')
                    ->where('withdraw_id', $info['withdraw_id'])
                    ->update([
                        'withdraw_status' => 2,
                        'withdraw_att_time' => date('Y-m-d H:i:s')
                    ]);
                Db::commit();
                return json(['code' => 200, 'msg' => '操作成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => '操作数据库失败']);
            }
        }else{
           return json(['code' => 100, 'msg' => $msg]);
        }
    }

    /**
     * 通过
     * @return \think\response\Json
     */
    public function adopt1(){
        $ids = input('ids');
        if($ids == ''){
            return json(['code' => 100, 'msg' => '请选择要操作的数据']);
        }
        $info = Db::table('up_withdraw')
            ->where('withdraw_id', 'in',$ids)
            ->select();
        foreach ($info as $key=>$vo){
            if($vo['withdraw_status']!=1){
                return json(['code' => 100, 'msg' => '请选择待审核的数据操作']);
            }
        }
        foreach ($info as $k=>$v){
            $data['withdraw_status'] = 2;
            Db::table('up_withdraw')->where('withdraw_id', $v['withdraw_id'])->update($data);
        }
        return json(['code' => 200, 'msg' => '操作成功']);
//        $info = Db::table('up_withdraw')->where('withdraw_id', $ids)->find();
//        // 提现手续费
//        $dis = Db::table('up_about')->where('about_id', 14)->value('about_tixian_dis');
//        $ratio = 100 - $dis;
//        $price = $info['withdraw_money'] * $ratio * 0.01; // 实际到账金额
//        $price = $info['withdraw_money']*0.006 ; // 实际到账金额

        // todo:1 调取微信/支付宝提现接口  2 提现成功修改提现申请状态  3 提现成功参入到order表  4 减用户余额
//        if($info['withdraw_type'] == 1){
//            Loader::import('tixian.Weixin',EXTEND_PATH,'.php');
//            $wxtx = new Weixin($this->wx_config);
//            $res = $wxtx->wxTiXian($info['withdraw_num'], $info['withdraw_openid'], $price);
//            $return_code = (string)$res->return_code;
//            $result_code = (string)$res->result_code;
//            $return_code = trim(strtoupper($return_code));
//            $result_code = trim(strtoupper($result_code));
//            if($return_code == 'SUCCESS' && $result_code == 'SUCCESS'){
//                $success = 1;
//            }else{
//                $success = 0;
//                $msg = (string)$res->return_msg;
//            }
//        }else{ // 支付宝
//            $data = [
//                'out_biz_no' => $info['withdraw_num'], // 订单号
//                'payee_account' => $info['withdraw_zh'], // 支付宝账号
//                'amount' => $price, // 交易金额
////                'payee_real_name' => $info['withdraw_rel_name'] // 真实姓名
//            ];
//            Loader::import('tixian.Ali',EXTEND_PATH,'.php');
//            $ali = new Ali($this->ali_config);
//            $request = $ali->aliTiXian($data);
//            if($request['code'] == 1){
//                $success = 1;
//            }else{
//                $success = 0;
//                // $result->$responseNode->sub_msg 这个参数 是返回的错误信息
//                $msg = $request['msg'];
//            }
//        }

//        if($success == 1){
//            //插入钱包明细
//            $result['user_id'] = $info['withdraw_user_id'];
//            $result['balance_type'] = $info['withdraw_type'];
//            $result['balance_time'] = date('Y-m-d H:i:s');
//            if($info['withdraw_type']==1){
//                $result['balance_title'] ="微信提现";
//            }elseif ($info['withdraw_type']==2){
//                $result['balance_title'] ="支付宝提现";
//            }
//            $result['balance_num'] = date('YmdHis') . str_pad(mt_rand(1, 99999999), 4, '0', STR_PAD_LEFT);
//            $result['balance_price'] = $info['withdraw_money'];
//            $result['balance_status'] = 2;
//            $result['balance_jia_jian'] = 1;
//            $result['balance_xs'] = 1;
//            Db::table('up_user_balance')->insertGetId($result);
//            Db::startTrans();
//            try{
//                // 修改提现订单状态和审核时间
//                Db::table('up_withdraw')
//                    ->where('withdraw_id', $info['withdraw_id'])
//                    ->update([
//                        'withdraw_status' => 2,
//                        'withdraw_att_time' => date('Y-m-d H:i:s')
//                    ]);
//                Db::commit();
//                return json(['code' => 200, 'msg' => '操作成功']);
//            }catch(\Exception $e){
//                Db::rollback();
//                return json(['code' => 100, 'msg' => '操作数据库失败']);
//            }
//        }else{
//            return json(['code' => 100, 'msg' => $msg]);
//        }
    }
    /**
     * 拒绝
     * @return \think\response\Json
     */
    public function refuse(){
        if(Request::instance()->isPost()) {
            $ids = input('id');
            $info = Db::table('up_withdraw')
                ->field('withdraw_money, withdraw_user_id')
                ->where('withdraw_id', $ids)
                ->find();
            Db::startTrans();
            try {
                $withdraw_yuanyin = input('param.withdraw_yuanyin');
                // 改变提现申请状态
                $data['withdraw_yuanyin'] = $withdraw_yuanyin;
                $data['withdraw_status'] = 3;
                Db::table('up_withdraw')->where('withdraw_id', $ids)->update($data);

                // 恢复用户被扣除的金额
                Db::table('up_u_user')->where('user_id', $info['withdraw_user_id'])->setInc('user_balance', $info['withdraw_money']);
                Db::commit();
                return json(['code' => 200, 'msg' => '操作成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        $withdraw_id = input('param.withdraw_id');
        $this->assign('withdraw_id',$withdraw_id);
        return $this->fetch();
    }
    /**
     * 批量拒绝
     * @return \think\response\Json
     */
    public function refuse1(){
        if(Request::instance()->isPost()) {
            $ids = input('ids');
            if($ids == ''){
                return json(['code' => 100, 'msg' => '请选择要操作的数据']);
            }
            $info = Db::table('up_withdraw')
                ->where('withdraw_id', 'in',$ids)
                ->select();
            foreach ($info as $key=>$vo){
                if($vo['withdraw_status']!=1){
                    return json(['code' => 100, 'msg' => '请选择待审核的数据操作']);
                }
            }
            foreach ($info as $k=>$v){
                $data['withdraw_status'] = 3;
                Db::table('up_withdraw')->where('withdraw_id', $v['withdraw_id'])->update($data);
                Db::table('up_u_user')->where('user_id', $v['withdraw_user_id'])->setInc('user_balance', $v['withdraw_money']);
            }
            return json(['code' => 200, 'msg' => '操作成功']);

//            Db::startTrans();
//            try {
//                $withdraw_yuanyin = input('param.withdraw_yuanyin');
//                // 改变提现申请状态
//                $data['withdraw_yuanyin'] = $withdraw_yuanyin;
//                $data['withdraw_status'] = 3;
//                Db::table('up_withdraw')->where('withdraw_id', $ids)->update($data);
//
//                // 恢复用户被扣除的金额
//                Db::table('up_u_user')->where('user_id', $info['withdraw_user_id'])->setInc('user_balance', $info['withdraw_money']);
//                Db::commit();
//                return json(['code' => 200, 'msg' => '操作成功']);
//            } catch (\Exception $e) {
//                Db::rollback();
//                return json(['code' => 100, 'msg' => '操作失败']);
//            }
        }
        $withdraw_id = input('param.withdraw_id');
        $this->assign('withdraw_id',$withdraw_id);
        return $this->fetch();
    }
    public function outExcel(){

        $user_ids = input('ids');
        if($user_ids == ''){
            return json(['code' => 100, 'msg' => '请选择要操作的用户']);
        }
        $lists =  Db::table('up_withdraw')->alias('a')
            ->join('up_u_user uuu','uuu.user_id = a.withdraw_user_id','left')
            ->field('uuu.user_username,uuu.user_phone,uuu.user_id,a.*')
            ->where('withdraw_id', 'IN', $user_ids)
            ->order('withdraw_id desc')
            ->select();
        foreach($lists as $k => $v){
            $lists[$k]['withdraw_id'] = "\t".$v['withdraw_id']."\t";
            $lists[$k]['withdraw_num'] = "\t".$v['withdraw_num']."\t";
            $lists[$k]['user_username'] = "\t".$v['user_username']."\t";
            $lists[$k]['user_phone'] = "\t".$v['user_phone']."\t";
            if($v['withdraw_status']==1){
                $lists[$k]['withdraw_status_name'] = "待审核";
            }elseif ($v['withdraw_status']==2){
                $lists[$k]['withdraw_status_name'] = "通过";
            }elseif ($v['withdraw_status']==3){
                $lists[$k]['withdraw_status_name'] = "未通过";
            }
            $lists[$k]['withdraw_create_time'] = "\t".$v['withdraw_create_time']."\t";
            $lists[$k]['withdraw_money'] = "\t".$v['withdraw_money']."\t";
            if($v['withdraw_type']==1){
                $lists[$k]['withdraw_type_name'] = "微信";
            }elseif ($v['withdraw_type']==2){
                $lists[$k]['withdraw_type_name'] = "支付宝";
            }
        }
        $cellname = [
            ['withdraw_id','ID',20,'LEFT'],
            ['withdraw_num','提现单号',20,'LEFT'],
            ['user_username','昵称',20,'LEFT'],
            ['user_phone','手机号',20,'LEFT'],
            ['withdraw_status_name','审核状态',20,'LEFT'],
            ['withdraw_create_time','提现时间',20,'LEFT'],
            ['withdraw_money','提现金额',20,'LEFT'],
            ['withdraw_type_name','提现方式',20,'LEFT']
        ];
        $res = exportExcel('用户提现列表', 'Looks', $cellname, $lists);
        return json($res);
    }
}